import { IPSAppDEMobCustomView, IPSAppViewEngine, IPSControl } from '@ibiz/dynamic-model-api';
import { ModelTool } from '../../../util';
import { MobCustomViewEngine } from '../../../engine';
import { IMobCustomViewController } from '../../../interface';
import { AppDEViewController } from './app-de-view-controller';

export class MobCustomViewController extends AppDEViewController implements IMobCustomViewController {
  /**
   * @description 视图实例
   * @type {IPSAppDEMobCustomView}
   * @memberof MobCustomViewController
   */
  public viewInstance!: IPSAppDEMobCustomView;

  /**
   * @description 视图引擎
   * @type {MobCustomViewEngine}
   * @memberof MobCustomViewController
   */
  public engine: MobCustomViewEngine = new MobCustomViewEngine();

  /**
   * @description 视图引擎初始化
   * @param {*} [opts={}]
   * @memberof MobCustomViewController
   */
  public engineInit(opts: any = {}) {
    if (App.isPreviewMode()) {
      return;
    }
    const appDataEntity = this.viewInstance.getPSAppDataEntity();
    const engineOptions = {
      view: this,
      keyPSDEField: appDataEntity?.codeName?.toLowerCase(),
      majorPSDEField: ModelTool.getAppEntityMajorField(appDataEntity)?.codeName?.toLowerCase(),
    };
    if (this.viewInstance.getPSControls() && (this.viewInstance.getPSControls() as IPSControl[]).length > 0) {
      const ctrlArray: Array<any> = [];
      (this.viewInstance.getPSControls() as IPSControl[]).forEach((item: IPSControl) => {
        if (!Object.is(item.controlType, 'lefttoolbar') && !Object.is(item.controlType, 'righttoolbar')) {
          ctrlArray.push({ name: item.name, ctrl: this.ctrlRefsMap.get(item.name) });
        }
      });
      Object.assign(engineOptions, { ctrl: ctrlArray });
    }
    if (
      this.viewInstance.getPSAppViewEngines() &&
      (this.viewInstance.getPSAppViewEngines() as IPSAppViewEngine[]).length > 0
    ) {
      const engineArray: Array<any> = [];
      (this.viewInstance.getPSAppViewEngines() as IPSAppViewEngine[]).forEach((item: IPSAppViewEngine) => {
        if (Object.is(item.engineCat, 'CTRL')) {
          engineArray.push(item.M);
        }
      });
      Object.assign(engineOptions, { engine: engineArray });
    }
    this.engine.init(engineOptions);
  }
}
